package com.xyht.sca_s.student_manage_system.modules.inform.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.SmsInform;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.SmsUserView;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.dto.SmsInformDetailAddDto;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.dto.SmsInformDetailUpdateDto;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.dto.SmsInformIdDto;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.vo.*;
import com.xyht.sca_s.student_manage_system.modules.inform.mapper.SmsInformMapper;
import com.xyht.sca_s.student_manage_system.modules.inform.mapper.SmsUserViewMapper;
import com.xyht.sca_s.student_manage_system.modules.inform.service.SmsInformService;
import com.xyht.sca_s.student_manage_system.modules.news.constant.CollectStatusConstant;
import com.xyht.sca_s.student_manage_system.modules.news.constant.LikesStatusConstant;
import com.xyht.sca_s.student_manage_system.modules.news.entity.SmsNewsInformCollect;
import com.xyht.sca_s.student_manage_system.modules.news.entity.SmsNewsInformLikes;
import com.xyht.sca_s.student_manage_system.modules.news.mapper.SmsNewsInformCollectMapper;
import com.xyht.sca_s.student_manage_system.modules.news.mapper.SmsNewsInformLikesMapper;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.common.util.TimeUtil.StringtoDate;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-12-04
 */
@Service
public class SmsInformServiceImpl extends ServiceImpl<SmsInformMapper, SmsInform> implements SmsInformService {

    @Resource
    private SmsInformMapper smsInformMapper;
    @Resource
    private SmsUserMapper smsUserMapper;
    @Resource
    private SmsNewsInformLikesMapper smsUserLikesMapper;
    @Resource
    private SmsNewsInformCollectMapper smsNewsInformCollectMapper;
    @Resource
    private SmsUserViewMapper smsUserViewMapper;
    @Resource
    private CacheUtil cacheUtil;
    @Resource
    private SmsOrgUserRelationMapper orgUserRelationMapper;
    @Resource
    private SmsOrgStructureMapper orgStructureMapper;
    @Resource
    private SmsRoleMapper roleMapper;

    //添加通告
    @Override
    public ResponseResult addInform(SmsInformDetailAddDto smsInformDetailAddDto, String issuerId) {
        //校验参数是否为空
        if (isNullOrEmpty(smsInformDetailAddDto.getEventTopic()) || isNullOrEmpty(smsInformDetailAddDto.getEventType())
                || isNullOrEmpty(smsInformDetailAddDto.getContent())
                || isNullOrEmpty(smsInformDetailAddDto.getNotificationType())
                || isNullOrEmpty(smsInformDetailAddDto.getIsBanner())
                || isNullOrEmpty(smsInformDetailAddDto.getNoticeType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (smsInformDetailAddDto.getIsBanner() == 1 && isNullOrEmpty(smsInformDetailAddDto.getBanner())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        List<SmsInform> informList = smsInformMapper.selectList(new QueryWrapper<SmsInform>()
                .lambda()
                .eq(SmsInform::getIsBanner, 1));
        if (informList != null && informList.size() > 5) {
            return CommonResult.failed(CommonCodeEnum.INFORM_BANNER_ERR);
        }

        SmsInform smsInform = new SmsInform();
        BeanUtils.copyProperties(smsInformDetailAddDto, smsInform);

        if (smsInformDetailAddDto.getNoticeType() == 1 && smsInformDetailAddDto.getOrgId() != null && smsInformDetailAddDto.getOrgId().size() > 0) {
            //设置组织
            smsInform.setOrgId(smsInformDetailAddDto.getOrgId().toString());
            smsInform.setRoleId("");
            smsInform.setPersonnelId("");
        } else if (smsInformDetailAddDto.getNoticeType() == 2 && smsInformDetailAddDto.getRoleId() != null && smsInformDetailAddDto.getRoleId().size() > 0) {
            //设置角色
            smsInform.setRoleId(smsInformDetailAddDto.getRoleId().toString());
            smsInform.setOrgId("");
            smsInform.setPersonnelId("");
        } else if (smsInformDetailAddDto.getNoticeType() == 3 && smsInformDetailAddDto.getPersonnelId() != null && smsInformDetailAddDto.getPersonnelId().size() > 0) {
            //设置人员
            smsInform.setPersonnelId(smsInformDetailAddDto.getPersonnelId().toString());
            smsInform.setOrgId("");
            smsInform.setRoleId("");
        } else {
            smsInform.setPersonnelId("");
            smsInform.setOrgId("");
            smsInform.setRoleId("");
        }

        smsInform.setStartTime(new Date());
        smsInform.setCreateTime(new Date());
        //有效
        smsInform.setState(smsInformDetailAddDto.getState());
        //赋值发布人就是登陆者
        smsInform.setIssuerId(issuerId);
        smsInformMapper.insert(smsInform);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getInformById(String id, String issuerId) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsInform smsInform = smsInformMapper.selectById(id);
        if (smsInform == null) {
            log.debug("查询失败,通知不存在");
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }
        if (smsInform.getEndTime() != null) {
            if (smsInform.getEndTime().compareTo(new Date()) < 0) {
                return CommonResult.failed(CommonCodeEnum.INFORM_TIME_EXPIRED);
            }
        }

        SmsInformVo smsInformVo = new SmsInformVo();
        BeanUtils.copyProperties(smsInform, smsInformVo);
        //浏览人保存
        SmsUserView smsUserView = new SmsUserView();
        smsUserView.setViewUserId(issuerId);
        smsUserView.setViewObjectId(id);
        smsUserView.setCreateTime(new Date());
        smsUserViewMapper.insert(smsUserView);
        //回显浏览人
        List<SmsExamineUserInfoVo> smsExamineUserInfoVos = new ArrayList<>();
        QueryWrapper<SmsUserView> smsUserViewQueryWrapper = new QueryWrapper<>();
        smsUserViewQueryWrapper
                .select("DISTINCT view_user_id");
        smsUserViewQueryWrapper.lambda().eq(SmsUserView::getViewObjectId, id);
        List<SmsUserView> smsUserViews = smsUserViewMapper.selectList(smsUserViewQueryWrapper);
        for (SmsUserView userView : smsUserViews) {
            SmsExamineUserInfoVo smsExamineUserInfoVo = new SmsExamineUserInfoVo();
            SmsUser smsUser = cacheUtil.getUserInfo(userView.getViewUserId());
            if (!isNullOrEmpty(smsUser)) {
                smsExamineUserInfoVo.setUsername(smsUser.getUsername());
                smsExamineUserInfoVo.setUserPic(smsUser.getUserPic());
                smsExamineUserInfoVo.setRealName(smsUser.getRealName());
                smsExamineUserInfoVo.setId(smsUser.getId());
            }
            smsExamineUserInfoVos.add(smsExamineUserInfoVo);
        }
        smsInformVo.setSmsExamineUserVo(smsExamineUserInfoVos);
        //浏览量
        QueryWrapper<SmsUserView> smsViewCountQueryWrapper = new QueryWrapper<>();
        smsViewCountQueryWrapper.lambda().eq(SmsUserView::getViewObjectId, id);
        Integer viewCount = smsUserViewMapper.selectCount(smsViewCountQueryWrapper);
        smsInformVo.setViewCount(viewCount);

        //点赞和收藏状态
        QueryWrapper<SmsNewsInformLikes> smsUserLikesQueryWrapper = new QueryWrapper<>();
        smsUserLikesQueryWrapper.lambda().eq(SmsNewsInformLikes::getLikeUserId, issuerId)
                .and(i -> i.eq(SmsNewsInformLikes::getInfoId, id));
        SmsNewsInformLikes smsNewsInformLikes = smsUserLikesMapper.selectOne(smsUserLikesQueryWrapper);
        if (!isNullOrEmpty(smsNewsInformLikes)) {
            smsInformVo.setLikesStatus(smsNewsInformLikes.getStatus());
        } else {
            smsInformVo.setLikesStatus(LikesStatusConstant.LIKES_STATUS_CANCEL);
        }
        QueryWrapper<SmsNewsInformCollect> smsUserCollectQueryWrapper = new QueryWrapper<>();
        smsUserCollectQueryWrapper.lambda().eq(SmsNewsInformCollect::getCollectUserId, issuerId)
                .and(i -> i.eq(SmsNewsInformCollect::getCollectInfoId, id));
        SmsNewsInformCollect smsNewsInformCollect = smsNewsInformCollectMapper.selectOne(smsUserCollectQueryWrapper);
        if (!isNullOrEmpty(smsNewsInformCollect)) {
            smsInformVo.setCollectStatus(smsNewsInformCollect.getCollectStatus());
        } else {
            smsInformVo.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_CANCEL);
        }

        String userName = smsInformMapper.selectUserName(smsInform.getIssuerId());
        if (userName == null) {
            userName = "用户+account";
        }
        //发布人的头像
        SmsUser smsUser = smsUserMapper.selectById(smsInform.getIssuerId());
        if (!isNullOrEmpty(smsUser)) {
            smsInformVo.setIssuerFace(smsUser.getUserPic());
        }

        //未读该为已读
        smsInformVo.setIsRead("1");
        smsInformVo.setIssuerId(userName);


        if (smsInform.getNoticeType() == 1) {
            List<SmsClassInformOrgVo> classInformVoList = new ArrayList<>();
            if (!smsInform.getOrgId().equals("")) {
                List<String> orgIdList = JSONObject.parseArray(smsInform.getOrgId(), String.class);
                if(orgIdList.isEmpty()){
                    smsInformVo.setClassInformOrgVoList(classInformVoList);
                }
                for (String orgId : orgIdList) {
                    if(isNullOrEmpty(orgId)){
                        continue;
                    }
                    SmsClassInformOrgVo smsClassInformOrgVo = new SmsClassInformOrgVo();
                    SmsOrgStructure smsOrgStructure = orgStructureMapper.selectById(orgId);
                    if (!isNullOrEmpty(smsOrgStructure)) {
                        smsClassInformOrgVo.setOrgId(smsOrgStructure.getId());
                        smsClassInformOrgVo.setOrgName(smsOrgStructure.getOrgName());
                    }

                    classInformVoList.add(smsClassInformOrgVo);
                }
            }
            smsInformVo.setClassInformOrgVoList(classInformVoList);
        }else if(smsInform.getNoticeType() == 2){
            List<SmsClassInformRoleVo> smsClassInformRoleVos = new ArrayList<>();
            if (!smsInform.getRoleId().equals("")) {
                List<String> RoleIdList = JSONObject.parseArray(smsInform.getRoleId(), String.class);
                for (String roleId : RoleIdList) {
                    if(isNullOrEmpty(roleId)){
                        continue;
                    }
                    SmsClassInformRoleVo smsClassInformRoleVo = new SmsClassInformRoleVo();
                    SmsRole smsRole = roleMapper.selectById(roleId);
                    if (!isNullOrEmpty(smsRole)) {
                        smsClassInformRoleVo.setRoleName(smsRole.getRoleName());
                        smsClassInformRoleVo.setId(smsRole.getId());
                    }

                    smsClassInformRoleVos.add(smsClassInformRoleVo);
                }
                smsInformVo.setClassInformRoleVoList(smsClassInformRoleVos);
            }
        } else if (smsInform.getNoticeType() == 3) {
            List<SmsExamineUserInfoVo> smsExamineUserInfoVo1s = new ArrayList<>();
            if (!smsInform.getPersonnelId().equals("")) {
                List<String> PersonnelIdList = JSONObject.parseArray(smsInform.getPersonnelId(), String.class);
                for (String personnel : PersonnelIdList) {
                    SmsExamineUserInfoVo smsExamineUserInfoVo = new SmsExamineUserInfoVo();
                    SmsUser smsUser1 = smsUserMapper.selectById(personnel);
                    if (!isNullOrEmpty(smsUser1)) {
                        smsExamineUserInfoVo.setRealName(smsUser1.getRealName());
                        smsExamineUserInfoVo.setId(smsUser1.getId());
                    }

                    smsExamineUserInfoVo1s.add(smsExamineUserInfoVo);
                }
                smsInformVo.setClassInformPersonVoList(smsExamineUserInfoVo1s);
            }
        }


        return CommonResult.success(smsInformVo);
    }

    @Override
    public ResponseResult updateInform(SmsInformDetailUpdateDto smsInformDetailUpdateDto, String issuerId) {
        if (isNullOrEmpty(smsInformDetailUpdateDto.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查询数据库中的通知
        SmsInform inform = smsInformMapper.selectById(smsInformDetailUpdateDto.getId());
        if (inform == null) {
            log.debug("通知不存在,修改失败");
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }

        SmsInform smsInform = new SmsInform();
        BeanUtils.copyProperties(smsInformDetailUpdateDto, smsInform);

        if (smsInformDetailUpdateDto.getNoticeType() == 1 && smsInformDetailUpdateDto.getOrgId() != null && smsInformDetailUpdateDto.getOrgId().size() > 0) {
            //设置组织
            smsInform.setOrgId(smsInformDetailUpdateDto.getOrgId().toString());
            smsInform.setRoleId("");
            smsInform.setPersonnelId("");
        } else if (smsInformDetailUpdateDto.getNoticeType() == 2 && smsInformDetailUpdateDto.getRoleId() != null && smsInformDetailUpdateDto.getRoleId().size() > 0) {
            //设置角色
            smsInform.setRoleId(smsInformDetailUpdateDto.getRoleId().toString());
            smsInform.setOrgId("");
            smsInform.setPersonnelId("");
        } else if (smsInformDetailUpdateDto.getNoticeType() == 3 && smsInformDetailUpdateDto.getPersonnelId() != null && smsInformDetailUpdateDto.getPersonnelId().size() > 0) {
            //设置人员
            smsInform.setPersonnelId(smsInformDetailUpdateDto.getPersonnelId().toString());
            smsInform.setOrgId("");
            smsInform.setRoleId("");
        } else {
            smsInform.setPersonnelId("");
            smsInform.setOrgId("");
            smsInform.setRoleId("");
        }
        //赋值发布人就是登陆者
        smsInform.setIssuerId(issuerId);
        smsInform.setUpdateTime(new Date());
        smsInform.setCreateTime(inform.getCreateTime());
        int result = smsInformMapper.updateById(smsInform);
        if (result == 0) {
            log.debug("修改失败");
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteInform(SmsInform smsInform) {
        if (isNullOrEmpty(smsInform.getId())) {
            log.debug("删除失败,通知不存在");
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }
        int result = smsInformMapper.deleteById(smsInform.getId());
        if (result == 0) {
            log.debug("删除失败");
            return CommonResult.failed(CommonCodeEnum.DELETE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getAllInform(String userId, String notificationType, Integer pageSize, Integer pageNum) {

        if (isNullOrEmpty(userId) || isNullOrEmpty(notificationType)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
//        QueryWrapper<SmsInform> queryWrapper = new QueryWrapper<>();
//        List<SmsInformVo> smsInformVos =new ArrayList<>();
//        List<SmsInform> informs = smsInformMapper.selectList(queryWrapper);
//        if (informs == null) {
//            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
//        }
        Page<SmsInform> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsInform> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsInform::getNotificationType, notificationType)
                .gt(SmsInform::getEndTime, new Date())
                .orderByDesc(SmsInform::getCreateTime);
        smsInformMapper.selectPage(page, queryWrapper);
//        int total = (int)page.getTotal();
        List<SmsInform> list = page.getRecords();
        List<SmsInformVo> smsInformVos = new ArrayList<>();
//        for (SmsInform smsInform : informs) {
        for (SmsInform smsInform : list) {
            String userName = smsInformMapper.selectUserName(smsInform.getIssuerId());
            if (userName == null) {
                userName = "用户+account";
            }
            //发布人的头像
            SmsUser smsUser = smsUserMapper.selectById(smsInform.getIssuerId());

            if (smsInform.getEndTime() != null) {
                if (smsInform.getEndTime().compareTo(new Date()) < 0) {
                    continue;
                }
            }
            if (notificationType.equals(smsInform.getNotificationType())) {
                if (!smsInform.getOrgId().equals("")) {
                    String[] orgIds = smsInformMapper.selectOrgIdByUserId(userId);
                    for (String orgId : orgIds) {
                        List<String> orgList = JSONObject.parseArray(smsInform.getOrgId(), String.class);
                        if (orgList.contains(orgId)) {
                            SmsInformVo smsInformVo = new SmsInformVo();
                            BeanUtils.copyProperties(smsInform, smsInformVo);
                            smsInformVo.setIssuerId(userName);
                            if (!isNullOrEmpty(smsUser)) {
                                smsInformVo.setIssuerFace(smsUser.getUserPic());//发布人头像
                            }

                            smsInformVos.add(smsInformVo);
                            break;
                        }
                    }
//                return CommonCodeEnum.SUCCESS.addData(smsInformVos);
                } else if (!smsInform.getRoleId().equals("")) {
                    String[] roleIds = smsInformMapper.selectRoleIdByUserId(userId);
                    for (String roleId : roleIds) {
                        List<String> roleList = JSONObject.parseArray(smsInform.getRoleId(), String.class);
                        if (roleList.contains(roleId)) {
                            SmsInformVo smsInformVo = new SmsInformVo();
                            BeanUtils.copyProperties(smsInform, smsInformVo);
                            smsInformVo.setIssuerId(userName);
                            if (!isNullOrEmpty(smsUser)) {
                                smsInformVo.setIssuerFace(smsUser.getUserPic());//发布人头像
                            }

                            smsInformVos.add(smsInformVo);
                            break;
                        }
                    }
//                return CommonCodeEnum.SUCCESS.addData(smsInformVos);
                } else if (!smsInform.getPersonnelId().equals("")) {
                    List<String> personnelList = JSONObject.parseArray(smsInform.getPersonnelId(), String.class);
                    if (personnelList.contains(userId)) {
                        SmsInformVo smsInformVo = new SmsInformVo();
                        BeanUtils.copyProperties(smsInform, smsInformVo);
                        smsInformVo.setIssuerId(userName);
                        smsInformVo.setIssuerFace(smsUser.getUserPic());//发布人头像
                        smsInformVos.add(smsInformVo);
                    }
//                return CommonCodeEnum.SUCCESS.addData(smsInformVos);
                }
            }
        }
        //分页
        List<SmsInformVo> subList = smsInformVos.stream().skip((pageNum - 1) * pageSize).limit(pageSize)
                .collect(Collectors.toList());
        return CommonResult.success(subList, smsInformVos.size());
//        return CommonCodeEnum.SUCCESS.addData(smsInformVos).addTotal(total);
//        return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
    }

    @Override
    public ResponseResult getAllBlackInform(String issuerId, Integer isBanner, Integer pageSize, Integer pageNum,
                                            String type, String search, String notificationType, String userId, String beginTime, String endTime) {
        if (isNullOrEmpty(issuerId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<SmsInform> queryWrapper = new QueryWrapper<>();
        List<SmsInformBlackVo> smsInformBlackVos = new ArrayList<>();
        List<SmsInform> informs = smsInformMapper.selectList(queryWrapper);
        if (informs == null) {
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }
        Page<SmsInform> page = new Page<>(pageNum, pageSize);
        queryWrapper.lambda().orderByDesc(SmsInform::getCreateTime);
        if (!isNullOrEmpty(isBanner)) {
            queryWrapper.lambda().eq(SmsInform::getIsBanner, isBanner);
        }
        if(!isNullOrEmpty(type)){
            queryWrapper.lambda().eq(SmsInform::getEventType,type);
        }
        if(!isNullOrEmpty(userId)){
            queryWrapper.lambda().eq(SmsInform::getIssuerId,userId);
        }
        if(!isNullOrEmpty(search)){
            queryWrapper.lambda().like(SmsInform::getEventTopic,search);
        }
        if(!isNullOrEmpty(notificationType)){
            queryWrapper.lambda().eq(SmsInform::getNotificationType,notificationType);
        }
        if(!isNullOrEmpty(beginTime)){
            Date bgTime = StringtoDate(beginTime);
            queryWrapper.lambda().ge(SmsInform::getStartTime,bgTime);
        }
        if(!isNullOrEmpty(endTime)){
            Date edTime = StringtoDate(endTime);
            queryWrapper.lambda().le(SmsInform::getStartTime,edTime);
        }

        smsInformMapper.selectPage(page, queryWrapper);
        List<SmsInform> list = page.getRecords();
        for (SmsInform smsInform : list) {
            SmsInformBlackVo smsInformBlackVo = new SmsInformBlackVo();
            String userName = smsInformMapper.selectUserName(smsInform.getIssuerId());
            if (userName == null) {
                userName = "用户+account";
            }
            BeanUtils.copyProperties(smsInform, smsInformBlackVo);
            if (smsInform.getEndTime() != null) {
                if (smsInform.getEndTime().compareTo(new Date()) < 0) {
                    //设置状态为过期
                    smsInformBlackVo.setState("0");
                } else {
                    //设置状态为有效
                    smsInformBlackVo.setState("1");
                }
            }
            if (!isNullOrEmpty(userName)) {
                smsInformBlackVo.setIssuerId(userName);
            }

            //发布人的头像
            SmsUser smsUser = smsUserMapper.selectById(smsInform.getIssuerId());
            if (!isNullOrEmpty(smsUser)) {
                smsInformBlackVo.setIssuerFace(smsUser.getUserPic());
            }


            smsInformBlackVos.add(smsInformBlackVo);
        }
        int total = (int) page.getTotal();
        return CommonResult.success(smsInformBlackVos, total);
    }

    @Override
    public ResponseResult getBanner() {
        List<SmsInform> informList = smsInformMapper.selectList(new QueryWrapper<SmsInform>()
                .lambda()
                .eq(SmsInform::getIsBanner, 1)
                .gt(SmsInform::getEndTime, new Date())
                .orderByDesc(SmsInform::getCreateTime));

        List<BannerVo> bannerVoList = informList.stream().map(smsInform -> {
            BannerVo bannerVo = new BannerVo();
            BeanUtils.copyProperties(smsInform, bannerVo);
            return bannerVo;
        }).collect(Collectors.toList());
        return CommonResult.success(bannerVoList);
    }

    @Override
    @Transactional
    public ResponseResult likes(String likeUserId, SmsInformIdDto informId) {
        if (isNullOrEmpty(likeUserId)) {
            return CommonResult.failed(CommonCodeEnum.UNAUTHORIZED);
        }
        SmsInform smsInform = smsInformMapper.selectById(informId.getId());
        if (isNullOrEmpty(smsInform)) {
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }

        //历史数据未设置点赞数处理
        if (smsInform.getLikes() == null) {
            smsInform.setLikes(0);
        }
        //根据通知id和用户id查数据
        QueryWrapper<SmsNewsInformLikes> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsNewsInformLikes::getLikeUserId, likeUserId)
                .and(i -> i.eq(SmsNewsInformLikes::getInfoId, informId.getId()));
        SmsNewsInformLikes userLikes = smsUserLikesMapper.selectOne(queryWrapper);
        //如果不存在数据则,则点赞,状态设置为1,新增数据并点赞数+1
        if (userLikes == null) {
            SmsNewsInformLikes smsNewsInformLikes = new SmsNewsInformLikes();
            smsNewsInformLikes.setLikeUserId(likeUserId);
            smsNewsInformLikes.setInfoId(informId.getId());
            smsNewsInformLikes.setSign(1);
            smsNewsInformLikes.setStatus(LikesStatusConstant.LIKES_STATUS_LIKES);
            smsNewsInformLikes.setCreateTime(new Date());
            smsUserLikesMapper.insert(smsNewsInformLikes);
            smsInform.setLikes(smsInform.getLikes() + 1);
            smsInformMapper.updateById(smsInform);
            return CommonResult.success(LikesStatusConstant.LIKES_STATUS_LIKES);
        }
        //1.如果存在数据,查看状态,
        //1.1状态为1,则取消点赞,点赞数-1.
        if (userLikes.getStatus() == 1) {
            //赞数-1
            if (smsInform.getLikes() != null && smsInform.getLikes() != 0) {
                smsInform.setLikes(smsInform.getLikes() - 1);
            }
            userLikes.setStatus(LikesStatusConstant.LIKES_STATUS_CANCEL);
            smsUserLikesMapper.updateById(userLikes);
            smsInformMapper.updateById(smsInform);
            return CommonResult.success(LikesStatusConstant.LIKES_STATUS_CANCEL);
        }
        //1.2状态为0,则点赞,点赞数+1.
        if (userLikes.getStatus() == 0) {
            //赞数+1
            smsInform.setLikes(smsInform.getLikes() + 1);
            smsInformMapper.updateById(smsInform);
            //
            userLikes.setStatus(LikesStatusConstant.LIKES_STATUS_LIKES);
            smsUserLikesMapper.updateById(userLikes);
        }
        return CommonResult.success(LikesStatusConstant.LIKES_STATUS_LIKES);
    }

    @Override
    @Transactional
    public ResponseResult collect(String collectUserId, SmsInformIdDto informId) {
        if (isNullOrEmpty(collectUserId)) {
            return CommonResult.failed(CommonCodeEnum.UNAUTHORIZED);
        }
        SmsInform smsInform = smsInformMapper.selectById(informId.getId());
        if (isNullOrEmpty(smsInform)) {
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }
        //历史数据未设置收藏数处理
        if (smsInform.getCollect() == null) {
            smsInform.setCollect(0);
        }
        //根据通知id和用户id查数据
        QueryWrapper<SmsNewsInformCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsNewsInformCollect::getCollectUserId, collectUserId)
                .and(i -> i.eq(SmsNewsInformCollect::getCollectInfoId, informId.getId()));
        SmsNewsInformCollect userCollect = smsNewsInformCollectMapper.selectOne(queryWrapper);
        //如果不存在数据则,则收藏,状态设置为1,新增数据,收藏+1
        if (userCollect == null) {
            SmsNewsInformCollect smsNewsInformCollect = new SmsNewsInformCollect();
            smsNewsInformCollect.setCollectUserId(collectUserId);
            smsNewsInformCollect.setCollectInfoId(informId.getId());
            smsNewsInformCollect.setSign(1);
            smsNewsInformCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_COLLECT);
            smsNewsInformCollect.setCreateTime(new Date());
            smsNewsInformCollectMapper.insert(smsNewsInformCollect);
            smsInform.setCollect(smsInform.getCollect() + 1);
            smsInformMapper.updateById(smsInform);
            return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_COLLECT);
        }
        //1.如果存在数据,查看状态,
        //1.1状态为1,则取消收藏,收藏数-1.
        if (userCollect.getCollectStatus() == 1) {
            //收藏数-1
            if (smsInform.getCollect() != null && smsInform.getCollect() != 0) {
                smsInform.setCollect(smsInform.getCollect() - 1);
            }
            userCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_CANCEL);
            smsNewsInformCollectMapper.updateById(userCollect);
            smsInformMapper.updateById(smsInform);
            return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_CANCEL);
        }
        //1.2状态为0,则收藏,收藏数+1.
        if (userCollect.getCollectStatus() == 0) {
            //收藏数+1
            smsInform.setCollect(smsInform.getCollect() + 1);
            smsInformMapper.updateById(smsInform);
            userCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_COLLECT);
            smsNewsInformCollectMapper.updateById(userCollect);
        }
        return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_COLLECT);
    }

    @Override
    public ResponseResult getClassInfo(String userId) {
        List<SmsClassInformOrgVo> classInformVoList = new ArrayList<>();
        List<SmsOrgUserRelation> smsOrgUserRelations = orgUserRelationMapper.selectList(new LambdaQueryWrapper<SmsOrgUserRelation>()
                .eq(SmsOrgUserRelation::getUserId, userId));
        if(smsOrgUserRelations.isEmpty()){
            return CommonResult.success(classInformVoList);
        }

        for (SmsOrgUserRelation smsOrgUserRelation : smsOrgUserRelations) {
            String orgId = smsOrgUserRelation.getOrgId();
            List<SmsOrgStructure> smsOrgStructures = orgStructureMapper.selectList(new LambdaQueryWrapper<SmsOrgStructure>()
                    .eq(SmsOrgStructure::getId, orgId)
                    .eq(SmsOrgStructure::getLevel, 6));//班级
            if(smsOrgStructures.isEmpty()){
                return CommonResult.success(classInformVoList);
            }

            for (SmsOrgStructure smsOrgStructure : smsOrgStructures) {
                SmsClassInformOrgVo smsClassInformOrgVo = new SmsClassInformOrgVo();
                smsClassInformOrgVo.setOrgId(smsOrgStructure.getId());
                smsClassInformOrgVo.setOrgName(smsOrgStructure.getOrgName());
                classInformVoList.add(smsClassInformOrgVo);
            }
        }
        return CommonResult.success(classInformVoList);
    }

}
